package com.hunanwenli.controller.setting;

import com.hunanwenli.entity.UserInfo;
import com.hunanwenli.service.login.FeignLoginService;
import com.hunanwenli.service.userInfo.FeignUserInfoService;
import com.hunanwenli.tool.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class SettingController {
    @Autowired
    private FeignLoginService feignLoginService;
    @Autowired
    private FeignUserInfoService feignUserInfoService;
    @RequestMapping(value = "/accountSettings",method = {RequestMethod.GET,RequestMethod.POST})
    public String accountSettings(HttpServletRequest request, Model model){
        String uuid = (String)request.getSession().getAttribute("uuid");
        request.getSession().getId();
        UserInfo userInfo = feignLoginService.getRedisUserInfo(uuid);
        model.addAttribute("userInfo",userInfo);
        return "setting/AccountSettings";
    }

    @RequestMapping(value = "/modified",method = RequestMethod.POST)
    public  String modified(String name,String sex,String birth,
                            String introduction,String city,
                            HttpServletRequest request,Model model){
        String uuid = (String)request.getSession().getAttribute("uuid");
        UserInfo userInfo = feignLoginService.getRedisUserInfo(uuid);
        if (!Tools.isNullOrEmpty(name)){
            userInfo.setName(name);
        }else if (!Tools.isNullOrEmpty(sex)){
            userInfo.setSex(sex);
        }else if (!Tools.isNullOrEmpty(birth)){
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date birthday = sdf.parse(birth);
                userInfo.setBirthday(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else if (!Tools.isNullOrEmpty(introduction)){
            userInfo.setAutograph(introduction);
        }else if (!Tools.isNullOrEmpty(city)){

            userInfo.setAddress(city);
        }
        String toJson = Tools.objectToJson(userInfo);
        System.out.println("============================="+toJson);
        Boolean isPutSuccess = feignUserInfoService.putUserInfo(toJson);
        if (isPutSuccess){
            return "forward:/accountSettings";
        }else {
            model.addAttribute("error","修改时发生异常，请重试");
            return "show";
        }
    }

}
